package com.xy.cloud.utils;

import com.xy.cloud.exception.BusinessException;

import java.security.MessageDigest;

public class SecureUtil {

    /**
     * md5加密
     * @param str 指定字符串
     * @return 加密后的字符串
     */
    public static String md5(String str) {
        str = (str == null ? "" : str);
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] btInput = str.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] strA = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                strA[k++] = hexDigits[byte0 >>> 4 & 0xf];
                strA[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(strA);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * sha1加密
     *
     * @param str 指定字符串
     * @return 加密后的字符串
     */
    public static String sha1(String str) {
        try {
            str = (str == null ? "" : str);
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] b = str.getBytes();
            md.update(b);
            byte[] b2 = md.digest();
            int len = b2.length;
            String strA = "0123456789abcdef";
            char[] ch = strA.toCharArray();
            char[] chs = new char[len * 2];
            for (int i = 0, k = 0; i < len; i++) {
                byte b3 = b2[i];
                chs[k++] = ch[b3 >>> 4 & 0xf];
                chs[k++] = ch[b3 & 0xf];
            }
            return new String(chs);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * sha256加密
     *
     * @param str 指定字符串
     * @return 加密后的字符串
     */
    public static String sha256(String str) {
        try {
            str = (str == null ? "" : str);
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));

            byte[] bytes = messageDigest.digest();
            StringBuilder builder = new StringBuilder();
            String temp;
            for (int i = 0; i < bytes.length; i++) {
                temp = Integer.toHexString(bytes[i] & 0xFF);
                if (temp.length() == 1) {
                    builder.append("0");
                }
                builder.append(temp);
            }

            return builder.toString();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * md5加盐加密: md5(md5(str) + md5(salt))
     * @param str 字符串
     * @param salt 盐
     * @return 加密后的字符串
     */
    public static String md5BySalt(String str, String salt) {
        return md5(md5(str) + md5(salt));
    }

}
